<template>
  <div>
    <el-dialog title="选择商品" :visible.sync="selectGoodsVisible" :close-on-press-escape="false" :show-close="false"
      width="70%">
      <div class="margin-container-list mar-l-0 mar-r-10">
        <div class="flex goods-list-layer">
          <div class="flex-item goods-list-ri">
            <!--顶部搜索 -->
            <div class="top-operate-default height-100 align-h-l">
              <div class="search-item">
                <label>商品搜索：</label>
                <el-select v-model="searchListQuery.textCol">
                  <el-option label="商品名称" value="title"></el-option>
                  <el-option label="商品货号" value="goodsCode" v-if="memberId === '' && supplierId === ''"></el-option>
                  <el-option label="商品条码" value="goodsBarCode" v-if="memberId === '' && supplierId === ''"></el-option>
                </el-select>
                <el-input @keyup.enter.native="doSearch" v-model="searchListQuery.textValue" placeholder="请输入关键词"
                  style="width: 220px">
                </el-input>
                <label class="mar-l-20">商品分类：</label>
                <el-cascader v-model="categoryIds" :props="{ checkStrictly: true }" :options="categoryData" clearable
                  placeholder="选择商品分类" filterable></el-cascader>
                <template v-if="memberId === '' && supplierId === ''">
                  <label class="mar-l-20">商品品牌：</label>
                  <el-select v-model="searchListQuery.brandId" clearable placeholder="请选择">
                    <el-option v-for="item in brandList" :key="item.brandId" :label="item.brandName"
                      :value="item.brandId">
                    </el-option>
                  </el-select>
                  <label>品牌分类：</label>
                  <el-select v-model="searchListQuery.brandCategoryId" clearable placeholder="请选择">
                    <el-option v-for="item in brandCategoryList" :key="item.brandCategoryId"
                      :label="item.brandCategoryName" :value="item.brandCategoryId">
                    </el-option>
                  </el-select>
                </template>
                <el-button-group class="mar-l-20">
                  <el-button type="primary" @click="doSearch">查询</el-button>
                  <el-button plain @click="doResetSearch">重置</el-button>
                </el-button-group>
              </div>
              <!--   <div class="search-item">
               
              </div> -->
            </div>
            <div class="pad-l-10 pad-r-10">
              <!-- 内容列表 -->
              <div class="table-container" v-loading="listLoading" element-loading-text="加载中">
                <div class="goods-index width-210 mar-b-10" :class="(index + 1) % 4 ? 'mar-r-17' : ''"
                  v-for="(item, index) in dataList" :key="index">
                  <div class="flex cursor-p goods-item" :class="item.show ? 'actived' : ''" @click="doSelect(item)">
                    <div v-if="item.show" class="actived-icon"><img :src="activedIcon" class="width-31 height-31"
                        border="0" /></div>
                    <label><img :src="item.mainImage" class="_user-avatar"></label>
                    <div class="font-12 pad-l-8 pad-t-6">
                      <div class="line-2" style="min-height: 32px;">
                        <template v-if="isAssociateSkuSearch !== 1">
                          <el-tag size="mini" v-if="item.skuFlag === 1" type="danger" effect="light">多</el-tag>
                        </template>
                        {{item.title}}
                      </div>
                      <div class="_line-1" style="min-height: 22px;">
                        <span v-if="isAssociateSkuSearch === 1">{{ item.skuDetail }}</span>
                      </div>
                      <template v-if="supplierId !== ''">
                        <div class="pad-t-5">￥{{ item.supplyPrice ? item.supplyPrice : '0.00' }}</div>
                      </template>
                      <template v-else>
                        <template v-if="isAssociateSkuSearch === 1">
                          <div class="pad-t-5">
                            ￥{{ item.sellPrice === null || item.sellPrice === '' ? 0.00:item.sellPrice }}</div>
                        </template>
                        <template v-else>
                          <div class="pad-t-5" v-if="item.skuFlag == 0">
                            ￥{{ item.sellPrice === null || item.sellPrice === ''? 0.00 :item.sellPrice }}</div>
                          <div class="pad-t-5" v-if="item.skuFlag == 1">
                            {{ item.priceRange }}
                          </div>
                        </template>
                      </template>
                    </div>
                  </div>
                </div>
                <div v-if="isShowEmptyMsg" class="font-color-9 flex flex-center height-per-100"
                  style="line-height: 380px;">
                  暂无商品数据
                </div>
              </div>
              <!-- 列表分页 -->
              <div class="pagination mar-t-10 pad-r-10 flex v-align-c">
                <div class="font-12 flex v-align-c">
                  <div>
                    <el-checkbox v-model="currentPaged" @change="currentPageEls">选择本页</el-checkbox>
                  </div>
                  <div class="pad-l-23">已选{{selectNumber}}个商品，共{{total}}个商品</div>
                </div>
                <div class="flex-item"></div>
                <div>
                  <pagination :total="total" :page.sync="searchListQuery.currentPage" :limit.sync="searchListQuery.size"
                    @pagination="initList" />

                </div>
              </div>
            </div>
            <div slot="footer" class="dialog-footer text-align-c small">
              <el-button @click="closeGoodsSelect">关闭</el-button>
              <el-button type="primary" @click="sureGoodsSelect">确定</el-button>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listBrand,
    listBrandCategory
  } from '@/api/user/enterpriseBrand'
  import {
    getByEnterpriseId
  } from '@/api/user/enterprise'
  import {
    getCommonSelectGoodsList,
    listGoodsCategory
  } from '@/api/goods/goods'

  import {
    pagingStoreWarehouseGoods
  } from '@/api/warehouse/warehouseGoods.js'
  import {
    pageSupplierGoods
  } from '@/api/goods/supplierGoods'
  import activedIcon from '@/assets/images/icon-sel.png'

  export default {
    props: {
      selectGoodsVisible: Boolean,
      hasSelectGoodsAndSku: {
        type: Array,
        default: null
      },
      // 是否关联sku查询
      isAssociateSkuSearch: {
        type: Number,
        default: 0
      },
      // 是否开启单或多规格
      skuFlag: {
        type: Number,
        default: null
      },
      // 商品状态：没传就不过滤，获取全部；1-上架，0-下架
      goodsStatus: Number,
      onConfirm: Function,
      onCancel: Function
    },
    data() {
      return {
        // 文本model
        // 商品来源model
        supplierType: '',
        // 供应商地区model
        areaCodes: [],
        // 零售商品分类model
        categoryIds: [],
        // 查询条件
        searchListQuery: {
          currentPage: 1,
          size: 20,
          textCol: 'title',
          brandCategoryId: '',
          brandId: '',
          textValue: ''
        },
        // 企业配置参数
        enterpriseConfig: {
          categorySeparate: '0',
          wholesaleCategoryAlias: '0'
        },
        // 序号
        goodsSortNo: null,
        // 零售商品分类集合
        categoryData: [],
        // 批发商品分类集合
        wholesaleCategoryData: [],
        // 品牌集合
        brandList: [],
        // 品牌分类集合
        brandCategoryList: [],
        // 供应商集合
        supplierList: [],
        // 供应商分类集合
        supplierCategoryList: [],
        total: 0,
        listLoading: true,
        dataList: [],
        multipleSelection: [],
        activedIcon: activedIcon,
        currentPaged: false,
        selectNumber: 0,
        selectedGoodsList: [],
        memberId: '',
        supplierId: '',
        isShowEmptyMsg: false
      }
    },
    // 初始化页面
    created() {
      // Object.assign(this.searchListQuery, this.defaultQuery)
      const enterpriseId = this.getEnterpriseId()
      if (this.getMemberId()) {
        this.memberId = this.getMemberId()
      }
      if (this.getSupplierId()) {
        this.supplierId = this.getSupplierId()
      }
      // 获取企业配置
      getByEnterpriseId(enterpriseId).then((response) => {
        this.enterpriseConfig = response.data
      })
      // 获取零售商品分类
      listGoodsCategory(enterpriseId).then(response => {
        this.categoryData = response.data
      })
      // // 获取批发商品分类
      // listWholesaleGoodsCategory(enterpriseId).then(response => {
      //   this.wholesaleCategoryData = response.data
      // })
      // // 获取供应商列表
      // listSupplier({
      //   enterpriseId: enterpriseId
      // }).then(response => {
      //   this.supplierList = response.data
      // })
      // // 获取供应商分类列表
      // listSupplierCategory({
      //   enterpriseId: enterpriseId
      // }).then(response => {
      //   this.supplierCategoryList = response.data
      // })
      // 获取品牌列表
      listBrand(enterpriseId).then(response => {
        this.brandList = response.data
      })
      // 获取品牌分类列表
      listBrandCategory(enterpriseId).then(response => {
        this.brandCategoryList = response.data
      })

      this.initList()

      // if (this.hasSelectGoodsAndSku && this.hasSelectGoodsAndSku.length > 0) {
      //   this.selectedGoodsList = this.hasSelectGoodsAndSku
      //   this.selectNumber = this.selectedGoodsList.length
      // }
    },
    mounted() {
      // const that = this
      // this.$bus.$on('selectComponentGoods', function(goodsSortNo) {
      //   that.goodsSortNo = goodsSortNo
      // })
    },
    methods: {
      // 初始化
      initList() {
        var that = this
        that.listLoading = true
        that.isShowEmptyMsg = false
        this.searchListQuery.title = ''
        this.searchListQuery.goodsCode = ''
        this.searchListQuery.goodsBarCode = ''
        that.searchListQuery[that.searchListQuery.textCol] = that.searchListQuery.textValue
        // 零售商品分类
        if (that.categoryIds && that.categoryIds.length > 0) {
          that.searchListQuery.oneCategoryId = that.categoryIds.length > 0 ? that.categoryIds[0] : ''
          that.searchListQuery.twoCategoryId = that.categoryIds.length > 1 ? that.categoryIds[1] : ''
          that.searchListQuery.threeCategoryId = that.categoryIds.length > 2 ? that.categoryIds[2] : ''
        }
        that.searchListQuery.isAssociateSkuSearch = that.isAssociateSkuSearch
        if (that.goodsStatus !== undefined) {
          that.searchListQuery.goodsStatus = that.goodsStatus
        }
        if (that.hasSelectGoodsAndSku && that.hasSelectGoodsAndSku.length > 0) {
          var goodsIds = []
          var skuIds = []
          that.hasSelectGoodsAndSku.forEach((item) => {
            if (that.isAssociateSkuSearch === 1) {
              if (item.skuId) {
                skuIds.push(item.skuId)
              } else {
                goodsIds.push(item.goodsId)
              }
            } else {
              goodsIds.push(item.goodsId)
            }
          })
          that.searchListQuery.notInGoodsIdsStr = goodsIds.join(',')
          that.searchListQuery.notInSkuIdsStr = skuIds.join(',')
        }
        // getMemberId()
        // skuIds
        // notInGoodsIds
        // goodsIds
        // notInSkuIds
        if (that.skuFlag !== undefined && that.skuFlag !== null) {
          that.searchListQuery.skuFlag = that.skuFlag
        }
        that.searchListQuery.enterpriseId = that.getEnterpriseId()
        if (that.memberId !== '') {
          that.searchListQuery.memberId = that.memberId
          that.searchListQuery.goodsGroupId = '-1'
          pagingStoreWarehouseGoods(that.searchListQuery).then(response => {
            if (response.isError) return
            that.total = response.data.total
            that.dataList = response.data.records
            that.isShowEmptyMsg = !that.total > 0
            var selectNum = 0
            that.dataList.forEach(item => {
              if (that.selectedGoodsList.length > 0) {
                item.show = that.selectedGoodsList.some(function(goodsDetail) {
                  if (that.isAssociateSkuSearch === 1) {
                    return (goodsDetail.goodsId === item.goodsId && goodsDetail.skuId === item.skuId)
                  } else {
                    return goodsDetail.goodsId === item.goodsId
                  }
                })
              } else {
                item.show = false
              }
              if (item.show) {
                selectNum = parseInt(selectNum) + 1
              }
            })
            that.currentPaged = that.dataList.length === selectNum
            that.listLoading = false
          })
        } else if (that.supplierId !== '') {
          that.searchListQuery.auditType = 2
          that.searchListQuery.supplierId = that.supplierId
          pageSupplierGoods(that.searchListQuery).then(response => {
            if (response.isError) return
            that.listLoading = false
            that.total = response.data.total
            that.dataList = response.data.records
            that.isShowEmptyMsg = !that.total > 0
            var selectNum = 0
            that.dataList.forEach(item => {
              if (that.selectedGoodsList.length > 0) {
                item.show = that.selectedGoodsList.some(function(goodsDetail) {
                  if (that.isAssociateSkuSearch === 1) {
                    return (goodsDetail.goodsId === item.goodsId && goodsDetail.skuId === item.skuId)
                  } else {
                    return goodsDetail.goodsId === item.goodsId
                  }
                })
              } else {
                item.show = false
              }
              if (item.show) {
                selectNum = parseInt(selectNum) + 1
              }
            })
            that.currentPaged = that.dataList.length === selectNum && that.total > 0
          })
        } else {
          that.searchListQuery.goodsTypes = '30,32'
          // 商品来源
          that.searchListQuery.goodsSource = 0
          getCommonSelectGoodsList(that.searchListQuery).then(response => {
            if (response.isError) return
            that.total = response.total
            that.dataList = response.records
            that.isShowEmptyMsg = !that.total > 0
            var selectNum = 0
            that.dataList.forEach(item => {
              if (that.selectedGoodsList.length > 0) {
                item.show = that.selectedGoodsList.some(function(goodsDetail) {
                  if (that.isAssociateSkuSearch === 1) {
                    return (goodsDetail.goodsId === item.goodsId && goodsDetail.skuId === item.skuId)
                  } else {
                    return goodsDetail.goodsId === item.goodsId
                  }
                })
              } else {
                item.show = false
              }
              if (item.show) {
                selectNum = parseInt(selectNum) + 1
              }
            })
            that.currentPaged = that.dataList.length === selectNum
            that.listLoading = false
          })
        }
      },
      // 查询事件
      doSearch() {
        this.searchListQuery.currentPage = 1
        this.initList()
      },
      // 重置事件
      doResetSearch() {
        this.searchListQuery.textCol = 'title'
        this.searchListQuery.textValue = ''
        this.searchListQuery.brandCategoryId = ''
        this.searchListQuery.brandId = ''
        this.categoryIds = []
        this.searchListQuery.oneCategoryId = ''
        this.searchListQuery.twoCategoryId = ''
        this.searchListQuery.threeCategoryId = ''
        this.doSearch()
      },
      // 选择本页
      currentPageEls() {
        var that = this
        console.log(that.currentPaged)
        if (that.currentPaged) {
          this.dataList.forEach(item => {
            var isSelect = that.selectedGoodsList.some(function(goodsDetail) {
              if (that.isAssociateSkuSearch === 1) {
                return (goodsDetail.goodsId === item.goodsId && goodsDetail.skuId === item.skuId)
              } else {
                return goodsDetail.goodsId === item.goodsId
              }
            })
            if (!isSelect) {
              that.doSelect(item, false)
            }
          })
          that.currentPaged = true
        } else {
          // 取消选择本页
          this.dataList.forEach(item => {
            item.show = false
            that.selectNumber = that.selectNumber - 1
            if (that.isAssociateSkuSearch === 1) {
              that.selectedGoodsList.splice(that.selectedGoodsList.findIndex(items => item.goodsId === items
                .goodsId && item.skuId === items.skuId), 1)
            } else {
              that.selectedGoodsList.splice(that.selectedGoodsList.findIndex(items => item.goodsId === items
                .goodsId), 1)
            }
            that.currentPaged = false
          })
        }
      },
      // 选择事件,并且是否要处理选择全部的，默认是：true
      doSelect(row, isProcessSelectAll) {
        if (isProcessSelectAll === undefined) {
          isProcessSelectAll = true
        }
        row.show = !row.show
        const changeData = row.show
        this.$delete(row, 'show')
        this.$set(row, 'show', changeData)
        const detailForm = {
          goodsSortNo: this.goodsSortNo,
          title: row.title,
          goodsId: row.goodsId,
          imgUrl: row.mainImage,
          price: row.sellPrice,
          stock: row.stock,
          salesNum: row.salesNum,
          distributeIncome: row.distributeIncome,
          skuFlag: row.skuFlag,
          anchorRatio: row.anchorRatio,
          putawayNum: row.putawayNum,
          anchorGoodsStatus: row.anchorGoodsStatus,
          anchorPlatformShopType: row.anchorPlatformShopType,
          quickAuthority: row.quickAuthority,
          tiktokAuthority: row.tiktokAuthority,
          income: row.anchorCommission,
          skuId: row.skuId,
          skuDetail: row.skuDetail
        }
        if (row.show) {
          this.selectNumber = this.selectNumber + 1
          this.selectedGoodsList.push(detailForm)
          // this.$bus.$emit('choiceDetailsGoods', detailForm)
        } else {
          this.selectNumber = this.selectNumber - 1
          if (this.isAssociateSkuSearch === 1) {
            this.selectedGoodsList.splice(this.selectedGoodsList.findIndex(item => row.goodsId === item.goodsId && row
              .skuId === item.skuId), 1)
          } else {
            this.selectedGoodsList.splice(this.selectedGoodsList.findIndex(item => row.goodsId === item.goodsId), 1)
          }
        }
        if (isProcessSelectAll) {
          var that = this
          var selectNum = 0
          that.dataList.forEach(item => {
            var isSelect = false
            if (that.selectedGoodsList.length > 0) {
              isSelect = that.selectedGoodsList.some(function(goodsDetail) {
                if (that.isAssociateSkuSearch === 1) {
                  return (goodsDetail.goodsId === item.goodsId && goodsDetail.skuId === item.skuId)
                } else {
                  return goodsDetail.goodsId === item.goodsId
                }
              })
            }
            if (isSelect) {
              selectNum = parseInt(selectNum) + 1
            }
          })
          that.currentPaged = that.dataList.length === selectNum
        }
      },
      closeGoodsSelect() {
        this.onCancel()
      },
      sureGoodsSelect() {
        if (!this.selectedGoodsList || this.selectedGoodsList.length === 0) {
          this.$message({
            message: '请先选择商品',
            type: 'warning'
          })
          return
        }
        this.onConfirm(this.selectedGoodsList)
        // this.currentPaged = false
        // this.selectedGoodsList = []
        // this.selectNumber = 0
      }
    }
  }
</script>

<style lang="less" scoped>
  .goods-list-layer {
    ul {
      margin: 0 2px 0 0;
      padding: 0;
      display: block;

      li {
        padding: 24px 0;
        font-size: 16px;
        width: 100px;
        text-align: center;
        list-style-type: none;
        color: #666;

        &.actived {
          background: #f8f8f8;
          color: #409eff;
        }
      }
    }

    /deep/ .search-item .el-select .el-input {
      width: 120px !important;
    }

    .goods-list-ri {
      background: #f8f8f8;
    }

    /deep/ .el-table {
      border-top: #e2e2e2 1px solid;
    }

    /deep/ .el-table th,
    /deep/ .el-table tr {
      background: #f8f8f8;
    }

    /deep/ .el-table th:hover,
    /deep/ .el-table tr:hover,
    /deep/ .el-table th:hover>td,
    /deep/ .el-table tr:hover>td {
      background: #f8f8f8 !important;
    }

    /deep/ .el-table td,
    /deep/ .el-table th.is-leaf {
      border-bottom: none;
    }

    /deep/ .el-loading-mask {
      background-color: rgba(255, 255, 255, 0.6) !important;
    }

    .table-container {
      min-height: 380px;

      &:after {
        content: '';
        display: block;
        clear: both;
        font-size: 0;
      }
    }

    .goods-index {
      float: left;
    }

    .goods-item {
      border-radius: 6px;
      background: #fdfffd;
      border: #f8f8f8 1px solid;
      overflow: hidden;
      position: relative;

      &.actived {
        border: #409eff 1px solid;
      }

      .actived-icon {
        position: absolute;
        right: 0;
        bottom: -6px;
      }
    }
  }

  .user-avatar {
    width: 75px;
    height: 75px;
    display: block;
    border-radius: 6px 0 0 6px;
  }

  .category-style {
    color: #3abbdb
  }

  .top-operate-default {
    background: none !important;

    /deep/ .search-item {
      padding: 0;

      label {
        width: 80px;
        text-align: right;
      }

      .el-input {
        width: 150px;
      }
    }
  }

  .align-h-l {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: space-evenly;
  }

  // 2行文字展示
  .line-2 {
    line-height: 1.4;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    word-break: break-word;
  }

  ._line-1 {
    /* line-height: 1.4; */
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    word-break: break-word;
  }

  ._user-avatar {
    width: 85px;
    height: 85px;
    display: block;
    border-radius: 6px 0 0 6px;
  }
</style>
